package com.sanshengshui.netty.oioAndnio;

/**
 * @author zyl
 * @description
 * @since 2024/7/17
 */
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Client {
    private String host;
    private int port;

    public Client(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        InetSocketAddress address = new InetSocketAddress(host, port);
        SocketChannel socketChannel = SocketChannel.open(address);

        // Set the socket to non-blocking mode
        socketChannel.configureBlocking(false);

        // Allocate a buffer for reading data
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            try {
                buffer.clear();
                int bytesRead = socketChannel.read(buffer);
                if (bytesRead > 0) {
                    buffer.flip();
                    byte[] bytes = new byte[buffer.remaining()];
                    buffer.get(bytes);
                    String response = new String(bytes, StandardCharsets.UTF_8);
                    System.out.println("Received from server: " + response);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, 0, 1, TimeUnit.SECONDS);

        // Send a simple message to the server
        String message = "Hello Server!\r\n";
        ByteBuffer writeBuffer = ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8));
        socketChannel.write(writeBuffer);

        // Keep the client running to read the server response
        System.out.println("Client started and waiting for server response...");
        Thread.currentThread().join();
    }

    public static void main(String[] args) {
        String host = "localhost";
        int port = 8080; // Replace with the appropriate port number

        try {
            for (;;){
                new Client(host, port).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

